package userserv

import (
	"codedef"
	"github.com/garyburd/redigo/redis"
	"rhelper"
	//"fmt"
	"log"
	"net/http"
	"task"
)

func checkTaskOfAccount(account string, taskId string) int {
	conn := rhelper.Pool().Get()
	defer conn.Close()

	tt, err := redis.String(conn.Do("HGET", rhelper.TaskHash+taskId, "type"))
	if err != nil {
		log.Println("checkTaskOfAccount failed, no task:", err)
		return codedef.ERR_DATABASE
	}

	if tt == "" {
		log.Println("checkTaskOfAccount failed, type is nil, no task:", err)
		return codedef.ERR_TASK_NOT_EXIST
	}

	return 0
}

func onStartTask(w http.ResponseWriter, r *http.Request) {
	var account string
	account = r.Header.Get("account")
	log.Printf("onStartTask, account:%s\n", account)

	var taskId = r.URL.Query().Get("tid")
	log.Println("onStartTask, taskId:", taskId)

	errcode := checkTaskOfAccount(account, taskId)
	if errcode != 0 {
		replyError(w, errcode)
		return
	}

	errcode = task.Mgr.StartTask(account, taskId)
	if errcode == 0 {
		w.WriteHeader(200)
	} else {
		replyError(w, errcode)
	}
}

func init() {
	myMux.muxHandlers.HandleFunc("/startTask", onStartTask)
}
